from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.utlis.common import user_login_data
from info.utlis.response_code import RET
from . import blue
from flask import render_template


#GET请求
#cid:分类 ID
#page:当前页码
#per_page:每页的数量
#全部选填
@blue.route('/news_list')
def get_new_list():

    #1 获取参数
    cid = request.args.get('cid',1)
    page =request.args.get('page',1)
    per_page = request.args.get('per_page',10)
    #2 校验参数(--int ---强转类型成功,说明是数字)
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg='参数错误')

    #3查询数据(filter(可能有,可能没有).order_by(时间降序).paginate(页码,每页的数量,出错是否要返回报错信息)
    #如果分类ID 传入的是1,那么就不需要设置filter.
    filter = []
    if cid != 1:
        filter.append(News.category_id==cid)
    try:
        #*filter 可以根据查询参数产生的查询条件语句展开
        paginates = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page,per_page,False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库错误')

    #获取需要的数据
    news_model_list = paginates.items
    total_page = paginates.pages
    current_page = paginates.page

    #模型转字典
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_dict())

    data = {
        'news_dict_li':news_dict_li,
        'total_page':total_page,
        'current_page':current_page
    }

    # 4 返回数据
    return  jsonify(errno =RET.OK,errmsg='OK',data= data)


#使用蓝图对象实现路由
@blue.route('/')
@user_login_data
def index():

    #一.用户信息
    user = g.user

    #二 ,点击排行
    #查询数据库--模型列表--模型转字典----拼接到data中---处理模板代码
    try:
        news_model_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_dict())

    #三, 分类信息
    categories = Category.query.all()

    category_dict_li = []
    for category in categories:
        category_dict_li.append(category.to_dict())
    # 如果查询到了 可以拼接要显示相关数据
    data = {
        'user':user.to_dict()if user else None,
        'news_dict_li':news_dict_li,
        'category_dict_li':category_dict_li
    }
    #将数据传递给模板
    return render_template('news/index.html',data = data)
#处理浏览器自动访问网站图标的路由

@blue.route('/favicon.ico')
def favicon_ico():
    return current_app.send_static_file('news/favicon.ico')